﻿using B.S.ProductionProject.Domain;
using B.S.ProductionProject.ErrorCode;
using B.S.ProductionProject.Read.WebAPI.Applications.Commands.ProductionPlanningCommand;
using B.S.ProductionProject.Read.WebAPI.Applications.Commands.ProductionScheduleDetailCommand;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.StaticFiles;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using SqlSugar;

namespace B.S.ProductionProject.Read.WebAPI.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class ManagementController : ControllerBase
    {
        private readonly IMediator _mediator;
        private readonly ISqlSugarClient db;
        private readonly ILogger<ManagementController> logger;

        public ManagementController(IMediator mediator, ISqlSugarClient db, ILogger<ManagementController> logger = null)
        {
            _mediator = mediator;
            this.db = db;
            this.logger = logger;
        }

        /// <summary>
        /// 获取计划信息
        /// </summary>
        /// <param name="request">请求</param>
        /// <returns>返回任务</returns>
        [HttpGet]
        public async Task<APIResult<APIPaging<ProductionPlanning>>> GetProduction([FromQuery] GetProductionPlanningCommand request)
        {
            logger.LogInformation("知识付费V领可能包括雷吉纳s");

            return await _mediator.Send(request);
        }

        /// <summary>
        /// 测试 ELK 日志接收报错信息的接口
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult TestELKLogging()
        {
            try
            {
                // 故意抛出异常
                throw new Exception("这是一个用于测试 ELK 日志的异常。");
            }
            catch (Exception ex)
            {
                // 记录异常日志
                logger.LogError(ex, "TestELKLogging 接口发生异常。");
                // 返回错误响应
                return StatusCode(500, "发生内部服务器错误。");
            }
        }

        /// <summary>
        /// 导出方法
        /// </summary>
        /// <returns>返回任务</returns>
        [HttpGet]
        public ActionResult ExportToExcel()
        {
            try
            {
                // 模拟查询数据，这里假设查询 User 表
                var data = db.Queryable<ProductionPlanning>().OrderBy(x => x.DocumentationDate).ToList();

                // 创建一个新的 Excel 工作簿
                IWorkbook wb = new XSSFWorkbook();

                //在Excel文件中创建工作表
                ISheet sheet = wb.CreateSheet("计划表");

                //在工作表中创建行(第一行,标题);
                IRow row = sheet.CreateRow(0);

                //创建单元格
                row.CreateCell(0).SetCellValue("计划主键");
                row.CreateCell(1).SetCellValue("单据主题");
                row.CreateCell(2).SetCellValue("单据编号");
                row.CreateCell(3).SetCellValue("关联项目");
                row.CreateCell(4).SetCellValue("自动生成订单");
                row.CreateCell(5).SetCellValue("制单人员");
                row.CreateCell(6).SetCellValue("制单日期");
                row.CreateCell(7).SetCellValue("备注");
                row.CreateCell(8).SetCellValue("是否删除");

                var index = 1;
                foreach (var item in data)
                {
                    row = sheet.CreateRow(index);

                    row.CreateCell(0).SetCellValue(item.ProductionPlanningId.ToString());
                    row.CreateCell(1).SetCellValue(item.DocumentSubject);
                    row.CreateCell(2).SetCellValue(item.DocumentNo);
                    row.CreateCell(3).SetCellValue(item.AssociatedItemNumber);
                    row.CreateCell(4).SetCellValue(item.AutomaticOrderGeneration ? "已生成" : "未生成");
                    row.CreateCell(5).SetCellValue(item.DocumentMaker);
                    row.CreateCell(6).SetCellValue(item.DocumentationDate.ToString("yyyy-MM-dd"));
                    row.CreateCell(7).SetCellValue(item.Remark);
                    row.CreateCell(8).SetCellValue(item.isDelete ? "删除" : "未删除");

                    index++;
                }

                //Excel的值
                byte[] buffer;
                //通过内存流读出Excel内容,转换为二进制数组
                using (MemoryStream ms = new MemoryStream())
                {
                    wb.Write(ms);
                    buffer = ms.ToArray();
                }

                //导出Excel  using  Microsoft.AspNetCore.StaticFiles;
                string excelMime = new FileExtensionContentTypeProvider().Mappings[".xlsx"];

                //导出
                return File(buffer, excelMime, "计划 表.xlsx");
            }
            catch (Exception ex)
            {
                // 处理异常
                Console.WriteLine($"导出 Excel 时出错: {ex.Message}");
            }

            return new EmptyResult();
        }

        /// <summary>
        /// 获取计划明细
        /// </summary>
        /// <param name="request">请求</param>
        /// <returns>返回任务</returns>
        [HttpGet]
        public async Task<APIResult<APIPaging<ProductionScheduleDetail>>> GetProductionScheduleDetail([FromQuery] GetProductionScheduleDetailCommand request)
        {
            return await _mediator.Send(request);
        }

        /// <summary>
        /// 根据ID查询计划
        /// </summary>
        /// <param name="request">请求</param>
        /// <returns>返回任务</returns>
        [HttpGet]
        public async Task<APIResult<List<ProductionPlanning>>> GetBYIdProduction([FromQuery] GetBYIdProductionPlanningCommand request)
        {
            return await _mediator.Send(request);
        }

        /// <summary>
        /// 根据ID查询计划明细
        /// </summary>
        /// <param name="request">请求</param>
        /// <returns>返回任务</returns>
        [HttpGet]
        public async Task<APIResult<List<ProductionScheduleDetail>>> GetBYIdProductionScheduleDetail([FromQuery] GetBYIdProductionScheduleDetailCommand request)
        {
            return await _mediator.Send(request);
        }


    }
}
